import { useEffect, useState, useMemo, useCallback } from "react";
import { useHistory } from "react-router-dom";
import { NavBar, Toast, Radio, Checkbox } from "antd-mobile";
import { MessageFill, ShopbagOutline } from "antd-mobile-icons";
import { isToken, setToken, removeToken, getToken } from "../tools/token";
import {
  lodaCart,
  lodaNumChange,
  randomPrd,
  removePrd,
} from "../serves/LodaCart";
import { filterImg } from "../tools";
import CartItem from "../component/cart/CartItem";
import CartNull from "../component/cart/CartNull";

function Cart() {
  const { push } = useHistory();
  const imgs =
    "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fblog%2F202105%2F19%2F20210519231308_f1de3.thumb.1000_0.jpg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1645766761&t=7f3a43e937e61cef357493097bdc300d ";

  const t =
    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjcmVhdGVkQXQiOjE2NDM1MjcwMjE4OTAsInVwZGF0ZWRBdCI6MTY0MzUyNzAyMTg5MCwiaWQiOjEsInVzZXJOYW1lIjoieW91cmVuQSIsInBhc3N3b3JkIjoiMTIzNDU2Iiwibmlja05hbWUiOiIiLCJnZW5kZXIiOiLmnKrnn6UiLCJhdmF0YXIiOiIiLCJhZGRyZXNzIjoiIiwiYXJlYSI6IiIsImlzTG9ja2VkIjowLCJzY29yZSI6MCwiYWdlIjowLCJiaXJ0aGRheSI6IiIsImlhdCI6MTY0Mzg3NTU4OSwiZXhwIjoxNjQzOTExNTg5fQ.wmlQnngrzBEDM8UE_3_Ew43WoP5xVGyafacZNpYS08E";

  const ranPrd = (remove=false) => {
    
    console.log(ranList);
    randomPrd().then((r) => {
      if(remove&&Array.isArray(remove)){
        let newarr=r.splice(0,remove.length)
        setRanList(ranList.filter(item=>{
          return remove.indexOf(item.id)==-1}).concat(newarr))
        return 
      }else{
        setRanList(r);
      }
      
    });
  };
  useEffect(() => {
    ranPrd()
    // setToken(t)
    lodaCart().then((r) => {
      setIst(true);
      if (r.code === -1) {
        isToken() ? removeToken() : null;
        return;
      }
      setList(
        r.data
          .map((item) => ({ ...item, is: false }))
          .filter((item) => item.product)
      );
      setIsstart(true);
    });
  }, []);

  const nowLoda = () => {
    //当页面商品数量改变时候，重新掉接口
    lodaCart().then((r) => {
      if (r.code === -1) {
        //如果出现问题，就直接跳转未登录状态并且清空list
        isToken() ? removeToken() : null;
        isStart(false);
        setList([]);
        return;
      }
      setList(
        r.data
          .filter((item) => item.product)
          .map((item, index) => {
            return {
              ...item,
              is: list.some((liItem) => liItem.id == item.id && liItem.is)
                ? true
                : false,
            };
          })
      );
    });
  };
  const [list, setList] = useState([]); //列表数据
  const [isRemove, setIsRemove] = useState(0); //表示是否删除状态
  const [isStart, setIsstart] = useState(false); //是否开始
  const [ist, setIst] = useState(false); //是否登录
  const [ranList, setRanList] = useState([]); //随机商品列表
  const [sd, setSd] = useState(0); //手动控制刷新
  const ck = (id, boolean) => {
    //单选控制的函数
    setList(
      list.map((item) => (item.id === id ? { ...item, is: boolean } : item))
    );
  };

  const isAll = useMemo(() => {
    //isall依赖于list，当list一旦改变就重新计算值
    return {
      is: list.every((item) => item.is) && list.length > 0,
      zong: list
        .filter((item) => item.is)
        .reduce(
          (a, b) => a + (b.product.price * 100 * (b.amount * 100)) / 10000,
          0
        ),
      num: list.filter((item) => item.is).reduce((a, b) => a + b.amount, 0),
    };
  }, [list]);
  const numChange = (id, num) => {
    //数量操作，这里是重新赋值了，接口好像是要传入正负值
    let v = list.find((item) => item.id === id);
    let l = num - v.amount;
    lodaNumChange(v.product.id, l).then((r) => {
      nowLoda();
    });
  };

  return (
    <div className="Cart">
      <NavBar
        className="cartNav"
        children="购物车"
        backArrow={false}
        right={
          <>
            <span
              className="bianji"
              style={{ color: `#${isRemove === 0 ? "666" : "FF2832"}` }}
              onClick={() => {
                setIsRemove(isRemove === 0 ? 1 : 0);
              }}
            >
              {isRemove === 0 ? "编辑" : "取消"}
            </span>
            <span className="huihua">{<MessageFill />}</span>
          </>
        }
      />
      <div className="cartContent">
        {list.length == 0 ? ( //这段代码是，页面载入，请求发送的时候显示正在加载中，请求完成顺带判断一下请求是否正确，不正确继续提示登录
          ist ? (
            <CartNull content={isStart ? "购物车空空如也" : "请先登录"} />
          ) : (
            <CartNull content="正在加载中" />
          )
        ) : null}
        {isToken()
          ? list.map((item) => (
              <CartItem
                key={item.id}
                ck={(boolean) => ck(item.id, boolean)}
                numChange={(num) => numChange(item.id, num)}
                is={item.is}
                imgs={item.product.coverImage}
                name={item.product.name}
                guige={item.product.desc}
                price={item.product.price}
                oddprice={item.oddprice}
                num={item.amount}
                jia={item.jia ? item.jia : null}
              />
            ))
          : null}

        <div className="tuijian">
          <h4 className="tj-tit">为您推荐</h4>
          <fieldset className="tj-tit2">
            <legend>
              {isToken() ? "购买了该商品了人还买了以下商品" : "热门销售"}
            </legend>
          </fieldset>
          <div className="tj-prd">
            {ranList.map((item) => (
              <div className="item" key={item.id}>
                <div className="img">
                  <img src={filterImg(item.coverImage)} alt="" />
                  <span className="haop">{item.onSale}人好评</span>
                  {/*  */}
                </div>
                <p className="name">
                  {item.name.length > 12
                    ? item.name.substr(0, 12) + "..."
                    : item.name}
                </p>
                <p className="desc">{item.desc}</p>
                <p className="price">
                  ￥{item.price}
                  <span
                    className="addCart"
                    onClick={() => {
                      lodaNumChange(item.id, 1).then((r) => {
                        if (r.code === -1) {
                          Toast.show({
                            icon: "fail",
                            content: "请先登录",
                          });
                        } else if (r.code === 1) {
                          Toast.show({
                            icon: "success",
                            content: "添加成功",
                          });
                          ranPrd([item.id])
                          nowLoda()
                        }
                      });
                    }}
                  >
                    {" "}
                    {<ShopbagOutline />}
                  </span>
                </p>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="jiesuan">
        <Checkbox
          checked={isAll.is}
          onChange={(val) => {
            setList(list.map((item) => ({ ...item, is: val })));
          }}
        >
          全选
        </Checkbox>
        <span>合计</span>
        <span>￥{isAll.zong}</span>
        <div
          className="tijiao"
          style={{
            backgroundColor: `#${isRemove === 0 ? "ff703a" : "FF2832"}`,
          }}
          onClick={() => {
            if (isRemove == 0) {
              //表示提交订单
              let PlaceOrder = list.filter((item) => item.is);

              if (PlaceOrder.length > 0) {
                //表示有选中的商品
                push({
                  pathname: "/Cart/tj",
                  state: { data: PlaceOrder },
                  query: { id: 666 },
                });
              }
            } else if (isRemove === 1) {
              //表示删除购物车商品
              list.forEach(item=>{
                if(item.is){
                  removePrd(item.id)
                }
              })
              setList(list.filter((item) => !item.is));
              setIsRemove(0);
              
            }
          }}
        >
          {isRemove == 0 ? "结算" : "删除"}({isAll.num})
        </div>
      </div>
    </div>
  );
}

export default Cart;
